﻿using System.Data;
using EntityFrameworkETL.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityFrameworkETL.SaveBatchedChanges;

namespace EntityFrameworkETL.Interceptors
{
    public class NonIdentityInsertCommandCacheInterceptor : IDbCommandInterceptor
    {
        public NonIdentityInsertCommandCacheInterceptor(Action<DbCommand> cacheCommand)
        {
            CacheCommand = cacheCommand;
        }

        public Action<DbCommand> CacheCommand { get; set; }


        public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
           
        }

        public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            CacheCommand(command);
            interceptionContext.SuppressExecution();
            interceptionContext.Result = 1;
        }

        public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
           
        }

        public IDictionary<string, DbCommandCacheItem> SaveBatchedEntityDictionary =
            new Dictionary<string, DbCommandCacheItem>();

        public static int FakePKs = 0;
        public static string PrimaryKeyName = "Id";
        public static Type PrimaryKeyType = typeof (Int32);

        public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            CacheCommand(command);
            interceptionContext.SuppressExecution();
            var dataTable = new DataTable("FakeResults");
            dataTable.Columns.Add(new DataColumn(PrimaryKeyName, PrimaryKeyType));
            var dr = dataTable.NewRow();
            FakePKs -= 1;
            dr[PrimaryKeyName] = FakePKs;
            dataTable.Rows.Add(dr);
            interceptionContext.Result = dataTable.CreateDataReader();
        }

        public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            throw new NotImplementedException();
        }

        public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            throw new NotImplementedException();
        }
    }
}
